// pages/addAddress/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:'',
    content:'',
    tempFilePaths: '',
    uploadFile: []
  },
  /**
   * 打开上传图片
   */
  uploadImage(e){
    var that = this
    var uploadFiles = []
    wx.showLoading({
      title: '加载中',
    })
    var token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        wx.hideLoading()
        const tempFilePaths = res.tempFilePaths
        that.setData({
          tempFilePaths: tempFilePaths
        })
        for(var i=0; i<tempFilePaths.length; i++){
          wx.uploadFile({
            url: 'http://127.0.0.1:8080/common/upload', //上传图片
            filePath: tempFilePaths[i],
            header: {
              'Authorization': token
            },
            name: 'file',
            success (res){
              const data = JSON.parse(res.data)
              uploadFiles.push(data['url'])
              that.setData({
                uploadFile: uploadFiles
              })
              console.log(that.data.uploadFile)
            },
          })
        }
      },
      fail(res){
        wx.hideLoading()
        wx.showToast({
          title: "取消上传",
          icon: 'none',
        })
      }
    })
  },

  titleInput: function(e) {
    this.setData({
      title: e.detail.value
    })
  },
  
  contentInput: function(e) {
    this.setData({
      content: e.detail.value
    })
  },
  
  addTopic: function() {
    var token = wx.getStorageSync('token');
    var user = wx.getStorageSync('user');
    var that = this;
    wx.request({
      url: 'http://127.0.0.1:8080/health/topic', // 添加话题接口
      method: 'post',
      header: {
        'content-type': 'application/json',  //这里注意POST请求content-type是小写，大写会报错
        'Authorization': token
      },
      data: {
        content: that.data.content,
        title: that.data.title,
        sponsorId: String(user.userId),
        sponsorName: user.userName,
        pics: that.data.uploadFile
      },
      success(res) {
        if (res.statusCode==200) {
          wx.showToast({
            title: "添加成功",
            icon: 'none',
          })
          var pages = getCurrentPages();
          var beforePage = pages[pages.length - 2];
          beforePage.onLoad(beforePage.options);
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })
  }
})